package com.tqjc.business.interactivewithscan.uils;

import com.tqjc.business.interactivewithscan.consts.ActionEnum;
import com.tqjc.business.interactivewithscan.consts.ExceptionEnum;
import com.tqjc.business.interactivewithscan.entity.DeviceCommandData;
import com.tqjc.business.interactivewithscan.entity.DeviceSocketClient;
import com.tqjc.business.interactivewithscan.entity.ScanDeviceData;
import com.tqjc.business.interactivewithscan.entity.ScanningData;
import com.tqjc.business.interactivewithscan.exception.CustomException;

import java.util.Date;

/**
 * @program: C20005_Xianggang_new
 * @description: 云台操作类
 * @author: Patienyon
 * @create: 2023-11-01 19:48
 **/
public class PTZUtils {
    /**
     * 查询云台状态，直到扫描完成
     *
     * @param device
     * @param socketClient
     * @param startStatus
     * @return
     */
    public static int queryQTZStatus(ScanDeviceData device, DeviceSocketClient socketClient, int startStatus) {
        String actionResult;
        DeviceCommandData<String> commandData;
        // 查询云台状态：que PTZStatus kp
        while (true) {
            commandData = new DeviceCommandData(device, socketClient, ActionEnum.YT_Que_PTZStatus, String.class);
            System.out.println(commandData.toString());
            actionResult = SocketCommandUtils.sendCommand(commandData);


            if (EmptyUtil.isEmpty(actionResult)) {
                return 0;
            } else {
                if (actionResult.startsWith("HB")) {
                    actionResult = actionResult.substring(2);
                }
                if (actionResult.endsWith("HB")) {
                    actionResult = actionResult.substring(0, actionResult.length() - 2);
                }
                //格式是否正确
                if (actionResult.startsWith("fb PTZStatus") && actionResult.endsWith("kp")) {
                    //状态
                    String s = actionResult.split(" ")[2];
                    int endStatus = Integer.parseInt(s);
                    if (startStatus == 0) {
                        if (endStatus == 3 || endStatus == 4) {
                            return endStatus;
                        }
                    } else {
                        //判断是否回到起始或结束位置（是否扫描完成）
                        if ((startStatus == 3 && endStatus == 4) || (startStatus == 4 && endStatus == 3)) {
                            return endStatus;
                        }
                    }
                } else {
                    return 0;
                }
            }
            CommonUtils.sleep(1000);
        }
    }

    public static String dispatchOrders(ScanDeviceData device, DeviceSocketClient socketClient, ActionEnum action) {
        DeviceCommandData<String> commandData = new DeviceCommandData(device, socketClient, action, String.class);
        String actionResult = SocketCommandUtils.sendCommand(commandData);
//        System.out.println("当前返回值为"+ actionResult);
        return dataFormatResult(actionResult);
    }

    public static String dispatchOrders(ScanDeviceData device, DeviceSocketClient socketClient, ActionEnum action, int err) {
        DeviceCommandData<String> commandData = new DeviceCommandData(device, socketClient, action, String.class);
        String actionResult = SocketCommandUtils.sendCommand(commandData);
        if (err == -1) {
            return actionResult;
        }
        if (!dataFormatCheck(actionResult)) {
            if (err == 10) {
                System.err.println("【" + device.getDeviceName() + "】执行【" + action.getActionName() + "】失败10次了！");
                return null;
            }
            CommonUtils.sleep(1000);
            return dispatchOrders(device, socketClient, action, err + 1);
        }
        return actionResult;
    }

    private static String dataFormatResult(String data) {
        if (EmptyUtil.isEmpty(data)) {
            return null;
        }
        if (data.startsWith("HB")) {
            data = data.substring(2);
        }
        if (data.endsWith("HB")) {
            data = data.substring(0, data.length() - 2);
        }
        if (!data.startsWith("fb ")) {
            return null;
        }
        if (!data.endsWith(" kp")) {
            return null;
        }
        data = data.replaceFirst(" ", "");
        int start = data.indexOf(" ");
        int end = data.lastIndexOf(" ");
        if (start == end) {
            return null;
        }
        return data.substring(start + 1, end);
    }

    private static boolean dataFormatCheck(String data) {
        if (EmptyUtil.isEmpty(data)) {
            return false;
        }
        if (data.startsWith("HB")) {
            data = data.substring(2);
        }
        if (data.endsWith("HB")) {
            data = data.substring(0, data.length() - 2);
        }
        if (!data.startsWith("fb ")) {
            return false;
        }
        if (!data.endsWith(" kp")) {
            return false;
        }
        String[] s = data.split(" ");
        if (s.length == 4 && "0".equals(s[2])) {
            return false;
        }
        return true;
    }

    /**
     * @param device
     * @param socketClient
     * @return
     */
    public static ScanningData scanning (ScanDeviceData device, DeviceSocketClient socketClient) {
        CommonUtils.sleep(5000);
        ScanningData scanningData = new ScanningData();
        scanningData.setScanningDate(new Date());
        // 查询云台起始状态
        int startStatus = 1;
        // 查询云台起始状态
        for (int i = 0; i < 3; i++) {
            startStatus = PTZUtils.queryQTZStatus(device, socketClient, 0);
            CommonUtils.sleep(1000);
        }
        if (startStatus == 0) {
            throw new CustomException(ExceptionEnum.YUNTAI_INITIAL_STATUS);
        }
        String rssStatus = "1";
        for (int i = 0; i < 3; i++) {
            // 查询系统状态：que RSStatus kp
            rssStatus = PTZUtils.dispatchOrders(device, socketClient, ActionEnum.YT_RSStatus);
            CommonUtils.sleep(1000);
        }
        if (EmptyUtil.isEmpty(rssStatus)) {
            throw new CustomException(ExceptionEnum.YUNTAI_RSSStatus_ERROR);
        }
        if (!rssStatus.equals("0") && !rssStatus.equals("1")) {
            throw new CustomException(ExceptionEnum.YUNTAI_RSSStatus_NON_CONFORMITY);
        }
        CommonUtils.sleep(1000);
        if (rssStatus.equals("0")) {
            System.out.println("启动激光雷达");
            // 云台激光雷达启动：cmd OpenPTZLidar kp
            if (PTZUtils.dispatchOrders(device, socketClient, ActionEnum.YT_Cmd_OpenPTZLidar, 0) == null) {
                throw new CustomException(ExceptionEnum.YUNTAI_OpenPTZLidar);
            }
        }
        CommonUtils.sleep(1000);
        // 云台激光雷达开始采集：cmd StartPTZLidar kp
        if (PTZUtils.dispatchOrders(device, socketClient, ActionEnum.YT_Cmd_StartPTZLidar, 0) == null) {
            throw new CustomException(ExceptionEnum.YUNTAI_StartPTZLidar);
        }
        CommonUtils.sleep(1000);
        // 查询云台状态：que PTZStatus kp
        if (PTZUtils.queryQTZStatus(device, socketClient, startStatus) == 0) {
            throw new CustomException(ExceptionEnum.YUNTAI_SCANNING_STATUS);
        }
        CommonUtils.sleep(5000);
        // 卡车与槽车四个顶点坐标
        String scanningArea = PTZUtils.dispatchOrders(device, socketClient, ActionEnum.YT_Que_ScanResult, 0);
        if (EmptyUtil.isEmpty(scanningArea)) {
            throw new CustomException(ExceptionEnum.YUNTAI_Que_ScanResult);
        }
        scanningData.setScanningArea(scanningArea);
        CommonUtils.sleep(1000);
        // 查询卡车车厢DEM
        String scanningDem = PTZUtils.dispatchOrders(device, socketClient, ActionEnum.YT_Que_TruckDEM, -1);
        if (EmptyUtil.isEmpty(scanningDem)) {
            throw new CustomException(ExceptionEnum.YUNTAI_Que_TruckDEM);
        }
        for (int i = 0; i < 100000; i++) {

        }
        // 窗口污染
//        String window = PTZUtils.dispatchOrders(device, socketClient, ActionEnum.YT_Que_WindowPollution);
//        if (EmptyUtil.isEmpty(window)) {
//            String msg = "【" + socketClient.getDevice().getDeviceName() + "】执行查询云台窗体污染错误！";
////            VoiceUtils.voice(msg);
//            throw new CustomException(ExceptionEnum.YUNTAI_RSSStatus_ERROR);
//        } else {
//            int i = Integer.parseInt(window);
//            if (i > 50 && i <= 70) {
//                String msg = "【" + socketClient.getDevice().getDeviceName() + "】窗体已重度污染，穿透率小于70，当前穿透率" + i + "，需要擦灰！";
//                System.err.println(msg);
////                VoiceUtils.voice(msg);
//            } else if (i <= 30) {
//                String msg = "【" + socketClient.getDevice().getDeviceName() + "】窗体污染严重，穿透率小于50，当前穿透率" + i + "，需要擦灰！";
////                VoiceUtils.voice(msg);
//                throw new CustomException(ExceptionEnum.YUNTAI_WindowPollution_ERROR);
//            }
//        }
        scanningData.setScanningDem(scanningDem);
        return scanningData;
    }

    public static void main(String[] args) {
        String s = "HBfb PTZStatus 3 kpHB";

        System.out.println(dataFormatResult(s));
    }
}